import java.util.Arrays;
import java.util.LinkedList;
import java.util.Stack;

public class MyStack implements IStack {

    private int[] elem;
    private int usedSize;//1. 记录有效元素个数
                         //2. 存储数据元素下标
    private static final int DEFAULT_CAPACITY = 10;

    public MyStack() {
        elem = new int[DEFAULT_CAPACITY];
    }

    //入栈
    @Override
    public void push(int x) {
        if (full()) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        this.elem[usedSize] = x;
        usedSize++;
    }

    //出栈
    @Override
    public int pop() throws StackEmptyException {
        if (empty()) {
            throw new StackEmptyException("栈为空！");
        }
        int old = elem[usedSize - 1];
        usedSize--;//相当于是删除
        // 如果里面为引用类型
        // elem[usedSize] = null;
        return old;
    }

    //查看栈顶元素
    @Override
    public int peek() {
        if (empty()) {
            throw new StackEmptyException("栈为空！");
        }
        return this.elem[usedSize -1];
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    //栈是否为空
    @Override
    public boolean empty() {
        return usedSize == 0;
    }

    //栈中元素是否满了
    @Override
    public boolean full() {
        return usedSize == elem.length;
    }
    //遍历打印
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
